import axios from "axios";
import ElMessage from "../composables/toast.js";

const server =axios.create({
    baseURL:'http://localhost:8080',
    timeout:600000
})
//添加axios 拦截器
server.interceptors.request.use(
    config => {
        console.log("axios请求拦截器执行了")
        const token = sessionStorage.getItem("token");
        if (token) {
            config.headers["token"] = token;
        } else {
            delete config.headers["token"];
        }
        return config; //放行请求
    },error=>{
        //失败的回调
        console.log(error)
        return Promise.reject(error);
    }
)

//添加axios响应拦截器
server.interceptors.response.use(response => {
    console.log(response);
    console.log("响应拦截器执行了")
    if (response.data.code === 1005) {
        ElMessage.error("请重新登录")
        sessionStorage.removeItem("token"); //移除token
        // Hash 路由跳转到登录页，避免历史模式路径不匹配
        window.location.hash = "#/login";
    }
    return response; //放行
},error=>{
    return Promise.reject(error);
})



export default server